<template>
  <div class="template-root-div">
    <div class="left-table">
      <div class="main">
        <mine-title>经典算法诊断</mine-title>
        <div class="content">
          <el-table
            class="table"
            :data="dictTableData"
            style="width: 100%"
            v-loading="dictLoading"
            @selection-change="handleDictSelectionChange"
            ref="multipleTable"
          >
            <!-- <el-table-column type="selection" width="45"></el-table-column> -->
            <el-table-column label="序号" show-overflow-tooltip width="60">
              <template slot-scope="scope">
                <span
                  >{{ scope.$index + (dictCurrentPage - 1) * dictPageSize + 1 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="算法名称"
              prop="algoName"
              show-overflow-tooltip
            >
              <template slot="header">
                <span>算法名称</span>
                <mine-table-search
                  @searchSubmit="searchDictSubmit"
                  name="algoName"
                ></mine-table-search>
              </template>
            </el-table-column>
            <el-table-column
              label="生成次数"
              prop="counts"
              show-overflow-tooltip
              width="120"
            >
            </el-table-column>
            <el-table-column
              label="创建时间"
              prop="createTime"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column label="操作" width="350">
              <template slot-scope="scope">
                <mine-button type="text" @click="editDetectList(scope.row)"
                  >详情</mine-button
                >
                <mine-button type="text" @click="codeCutDialog(scope.row)"
                  >代码裁剪</mine-button
                >
                <mine-button
                  type="text"
                  @click="historyVersionDialog(scope.row)"
                  >历史版本</mine-button
                >
                <mine-button
                  type="text"
                  v-if="scope.row.modelCode && scope.row.testFile"
                  @click="testDialog(scope.row)"
                  >测试</mine-button
                >
              </template>
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="dictNumberChange"
            :total="dictTotal"
            :page-size="dictPageSize"
            :current-page="dictCurrentPage"
          >
          </mine-pagination>
          <!-- 弹框区 -->
          <!-- 详情弹框区 -->
          <mine-dialog
            :top="'4vh'"
            :dialogFormVisible="editFlag"
            :width="'800px'"
            :showClose="true"
            :title="'详情'"
            @close="closeEditDialog"
          >
            <EditDialog
              slot="option"
              v-if="editFlag"
              :rowData="tableRowData"
              @close="closeEditDialog"
            ></EditDialog>
          </mine-dialog>
          <!-- 代码裁剪弹框 -->
          <mine-dialog
            :top="'4vh'"
            :dialogFormVisible="codeCutFlag"
            :width="'800px'"
            :showClose="true"
            :title="'代码裁剪'"
            @close="closeCodeCutDialog"
          >
            <template slot="option">
              <el-form ref="codeCutFormRef" :model="form" :rules="form.rules">
                <el-table
                  class="table border-table"
                  :data="form.tableData"
                  style="width: 100%"
                  ref="multipleTable"
                  @selection-change="codeCutCheckboxSelection"
                >
                  <!-- v-loading="loading"
                :height="tableHeight" -->
                  <el-table-column type="selection"> </el-table-column>
                  <el-table-column prop="name" label="名称"> </el-table-column>
                  <el-table-column prop="id" label="参数">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'tableData[' + scope.$index + '].id'"
                        :rules="
                          codeCutSelected.length &&
                          codeCutSelected.indexOf(scope.row) !== -1
                            ? form.rules.id
                            : []
                        "
                      >
                        <el-select
                          v-model="scope.row.id"
                          placeholder="请选择"
                          clearable
                          size="small"
                        >
                          <el-option
                            v-for="item in scope.row.parametersList"
                            :key="item.id"
                            :label="item.parameters"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="占比">
                    <template slot-scope="scope">
                      <el-form-item
                        :prop="'tableData[' + scope.$index + '].rate'"
                        :rules="
                          codeCutSelected.length &&
                          codeCutSelected.indexOf(scope.row) !== -1
                            ? form.rules.rate
                            : []
                        "
                      >
                        <el-input-number
                          size="small"
                          v-model="scope.row.rate"
                          :min="0"
                          :max="100"
                        ></el-input-number>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
              <div class="footer-bottom">
                <el-button type="primary" size="small" @click="codeCutConfirm"
                  >裁剪生成</el-button
                >
                <el-button type="primary" size="small" @click="codeCutCancel"
                  >取消</el-button
                >
              </div>
            </template>
          </mine-dialog>
          <!-- 测试按钮弹框 -->
          <mine-dialog
            :top="'4vh'"
            :dialogFormVisible="testResultFlag || historyVersionFlag"
            :width="'1200px'"
            :showClose="true"
            :title="rowData.algoName || '诊断模型'"
            @close="close"
          >
            <TestResult
              v-if="testResultFlag"
              slot="option"
              :testResultFlag="testResultFlag"
              @changeFlag="close"
              :rowData="rowData"
            ></TestResult>
            <HistoryVersion
              v-if="historyVersionFlag"
              slot="option"
              :historyVersionFlag="historyVersionFlag"
              @changeFlag="close"
              :rowData="rowData"
            ></HistoryVersion>
          </mine-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import qs from "qs";
import mineDialog from "../../../../components/mine-dialog.vue";
import TestResult from "./components/testResult.vue";
import HistoryVersion from "./components/historyVersion.vue";
import EditDialog from "./components/editDialog.vue";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  components: { mineDialog, TestResult, EditDialog, HistoryVersion },
  data() {
    return {
      tableHeight: window.innerHeight - 330,
      // left-table参数
      dictListQuery: { type: 1 }, // 这里type为设1, 标记为诊断页面，为2，标记为预测页面
      dictTableData: [],
      dictTotal: 0,
      dictPageSize: 10,
      dictCurrentPage: 1,
      dictMultipleSelection: [],
      dictLoading: false,

      // right-table参数
      optionListQuery: { type: 1 },
      optionTableData: [],
      optionTotal: 0,
      optionPageSize: 10,
      optionCurrentPage: 1,
      optionMultipleSelection: [],
      optionLoading: false,
      currentRowTemplateId: "", // 当前行的templateId
      form: {
        tableData: [],
        rules: {
          rate: [{ required: true, message: "请输入" }],
          id: [{ required: true, message: "请选择" }],
        },
      },
      codeCutSelected: [], // 复选框选中的项
      // title: "基于分类随机森林算法废弃处理设备的故障诊断模型",
      testResultFlag: false,
      historyVersionFlag: false,
      rowData: {}, // 点击测试按钮拿到当前行数据
      codeCutFlag: false,
      editFlag: false, // 编辑弹框
      tableRowData: {}, // 表格当行数据
    };
  },
  methods: {
    closeEditDialog() {
      this.editFlag = false;
      this.loadData();
    },
    closeCodeCutDialog() {
      this.codeCutFlag = false;
    },
    close() {
      this.testResultFlag = false;
      this.historyVersionFlag = false;
    },
    // 打开高校测试弹框
    testDialog(record) {
      this.testResultFlag = true;
      this.rowData = record;
    },
    // 打开历史版本弹框
    historyVersionDialog(record) {
      this.historyVersionFlag = true;
      this.rowData = record;
    },
    // 抽屉中复选框选中的项
    codeCutCheckboxSelection(list) {
      this.codeCutSelected = list;
    },
    async getLightList() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/algoTemplateCondition/getConditionByParams",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { algoTemplateId: _self.currentRowTemplateId },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              result.data.forEach((item) => {
                item.id = item.parametersList[0].id;
                item.rate = 1;
              });
              _self.form.tableData = result.data;
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/algoTemplateCondition/getConditionByParams",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            { algoTemplateId: this.currentRowTemplateId },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              // 选项默认赋值
              res.data.forEach((item) => {
                item.id = item.parametersList[0].id;
                item.rate = 1;
              });
              this.form.tableData = res.data;
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "getCheckboxListDialog",
          this.currentRowTemplateId
        );
        if (res.data.status === 200) {
          // 选项默认赋值
          res.data.data.forEach((item) => {
            item.id = item.parametersList[0].id;
            item.rate = 1;
          });
          this.form.tableData = res.data.data;
        }
      }
    },
    searchDictSubmit(value) {
      if (value.key === "algoName") {
        this.dictListQuery.algoName = value.value;
      }
      if (value.key === "language") {
        this.dictListQuery.language = value.value;
      }
      if (value.key === "purpose") {
        switch (value.value) {
          case "否":
            this.dictListQuery.purpose = 0;
            break;
          case "是":
            this.dictListQuery.purpose = 1;
            break;
        }
      }
      this.loadDictData(true);
    },
    async loadData(flag) {
      await this.loadDictData(flag);
    },
    addDict() {
      //   this.$store.commit("SET_DICT_NUMBER", Number(this.dictTotal));
      this.$router.push({
        path: "/code/addDetect",
        query: {
          isCut: true,
        },
      });
    },
    async deleteDict() {
      this.$mineConfirm("确认要删除", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.dictMultipleSelection.map((item) => item.id);
          // .join(",");
          this.dictLoading = true;
          let res = {};
          let _self = this;
          if (_self.$qwebUtil.isQtClient) {
            const uuid = _self.$qwebUtil.generateRandomUUID();
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: "/algoTemplateFile/deleteByIds",
                  RequestMethod: "post",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: {
                    ids: ids,
                    type: 1,
                  },
                  isStringParam: true,
                  requestId: uuid,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                _self.dictLoading = false;
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  _self.$message.success("删除成功");
                } else {
                  _self.$message.error(result.msg || "删除失败");
                }
              });
            }
          } else if (this.$webview2.isWPF) {
            const uuid = this.$webview2.generateRandomUUID();
            await this.$webview2.sendWebView2(
              "/algoTemplateFile/deleteByIds",
              "post",
              "application/json;charset=UTF-8",
              qs.stringify(
                {
                  ids: ids,
                  type: 1,
                },
                { indices: false }
              ),
              true,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data.response;
                // TODO： 定制后台数据处理
                if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                  this.$message.success("删除成功");
                } else {
                  this.$message.error(res.msg || "删除失败");
                }
                this.dictLoading = false;
              },
              { once: true }
            );
          } else {
            try {
              const res = await this.$store.dispatch("detectBatchDelete", {
                ids: ids,
                type: 1,
              });
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                // await this.loadData(true);
              } else {
                this.$message.error(result.msg || "删除失败");
              }
            } catch (e) {
              console.error(e);
            }
            this.dictLoading = false;
          }
        })
        .catch(() => {});
    },
    async loadDictData(flag, refresh = false) {
      if (flag) {
        this.dictCurrentPage = 1;
      }
      if (refresh) {
        this.dictListQuery = {};
      }
      const params = {
        ...this.dictListQuery,
        page: this.dictCurrentPage,
        pageSize: this.dictPageSize,
        type: 1,
      };
      this.dictLoading = true;
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/algoTemplateFile/pageList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(params, { indices: false }),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            // console.error('received','/feCanvas/pageList')
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            _self.dictLoading = false;
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.dictTableData = result.data.list ? result.data.list : [];
              _self.dictTotal = result.data.rowCount || 0;
            } else {
              _self.dictTableData = [];
              _self.total = 0;
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/algoTemplateFile/pageList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(params, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200) {
              this.dictTableData = res.data.list ? res.data.list : [];
              this.dictTotal = res.data.rowCount || 0;
            } else {
              this.dictTableData = [];
              this.total = 0;
            }
            this.dictLoading = false;
          },
          { once: true }
        );
      } else {
        try {
          const res = await this.$store.dispatch(
            "detectPageList",
            qs.stringify(params, { indices: false })
          );
          const result = res.data || {};
          // TODO： 定制后台数据处理
          if (result.success) {
            const data = result.data;
            this.dictTableData = data.list ? data.list : [];
            this.dictTotal = data.rowCount || 0;
          } else {
            this.dictTableData = [];
            this.total = 0;
          }
        } catch (e) {
          console.error(e);
        }
        this.dictLoading = false;
      }
    },
    // 多选
    handleDictSelectionChange(selection) {
      this.dictMultipleSelection = selection;
    },
    dictNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.dictPageSize = val.pageSize;
          this.loadDictData(true);
          break;
        case "currentPage":
          this.dictCurrentPage = val.currentPage;
          this.loadDictData(false);
          break;
        default:
          break;
      }
    },
    // 代码诊断列表编辑
    editDetectList(data) {
      this.editFlag = true;
      this.tableRowData = data;
    },
    // 右侧下载抽屉
    codeCutDialog(record) {
      this.currentRowTemplateId = record.id;
      this.codeCutFlag = !this.codeCutFlag;
      this.getLightList();
    },
    //
    async codeCutConfirm() {
      if (this.codeCutSelected.length === 0)
        return this.$message.warning("请选择数据！");
      await this.$refs.codeCutFormRef.validate();
      // 拿到完整数据
      let t = this.codeCutSelected.map((item) => {
        return {
          algoConditionId: item.id,
          rate: item.rate,
        };
      });
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/algoTemplateCondition/selectAlgoTemplateVersion?algoTemplateId=${_self.currentRowTemplateId}&type=1`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: t,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              // 文件下载
              _self.codeCutFlag = false;
            } else {
              _self.$message.error(result.msg);
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/algoTemplateCondition/selectAlgoTemplateVersion?algoTemplateId=${this.currentRowTemplateId}&type=1`,
          "post",
          "application/json;charset=UTF-8",
          t,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.success) {
              // 文件下载
              this.codeCutFlag = false;
            } else {
              this.$message.error("服务器请求错误！");
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("algoTemplateVersionConfirm", {
          algoTemplateId: this.currentRowTemplateId,
          list: t,
        });
        console.log(res);
        if (res.status === 200) {
          this.$message.success("裁剪生成成功");
          this.codeCutFlag = false;
        } else {
          this.$message.warning(res.msg);
        }
      }
    },
    codeCutCancel() {
      this.codeCutFlag = false;
    },
  },
  mounted() {
    this.loadData();
  },
};
</script>

<style scoped lang="less">
.template-root-div {
  display: flex;
}

.left-table {
  //   flex: 1;
  width: 100%;
  height: 100%;
}

.checkbox {
  padding: 0px 20px;
  .el-col {
    margin-bottom: 10px;
  }
}
.footer-bottom {
  // position: fixed;
  // right: 20px;
  // bottom: 20px;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.codeCut-rate {
  font-size: 14px;
  text-align: center;
  line-height: 40px;
}
/deep/ .el-dialog .el-dialog__body {
  padding-top: 0px;
}
/deep/.el-table .cell {
  height: 40px;
  line-height: 40px;
}
/deep/.el-dialog__header {
  padding: 10px 20px 10px;
}
</style>
